<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="套餐名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入套餐名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-present" size="mini" :disabled="single"
          @click="handleGivePackage">赠送套餐</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="rightsList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="套餐名称" prop="name" min-width="200" show-overflow-tooltip />
      <el-table-column label="权益详情" prop="detail" min-width="200" show-overflow-tooltip />
      <el-table-column label="图片" min-width="200" align="center">
        <template slot-scope="scope">
          <div v-if="getImageList(scope.row.images || scope.row.image) && getImageList(scope.row.images || scope.row.image).length" class="image-preview">
            <el-image v-for="(img, index) in getImageList(scope.row.images || scope.row.image).slice(0, 3)" :key="img + index"
              :src="getImageUrl(img)" :preview-src-list="getImageList(scope.row.images || scope.row.image).map(img => getImageUrl(img))"
              fit="cover" class="image-preview__item" />
            <span v-if="getImageList(scope.row.images || scope.row.image).length > 3" class="image-preview__more">+{{
              getImageList(scope.row.images || scope.row.image).length - 3 }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="price" width="120" align="center">
        <template slot-scope="scope">
          <span>¥{{ scope.row.price !== undefined && scope.row.price !== null ? Number(scope.row.price).toFixed(2) : (scope.row.parice !== undefined && scope.row.parice !== null ? Number(scope.row.parice).toFixed(2) : '0.00') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品规格" prop="rights_goods" min-width="250" align="center">
        <template slot-scope="scope">
          <div v-if="getRightsGoodsList(scope.row).length">
            <el-tag v-for="(item, index) in getRightsGoodsList(scope.row)" :key="index" size="mini"
              style="margin-right: 5px; margin-bottom: 3px;">
              {{ item.specName || getSpecName(item.specId) }}
            </el-tag>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="120" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="CreatedAt" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.CreatedAt ? parseTime(scope.row.CreatedAt) : (scope.row.created_at ? parseTime(scope.row.created_at) : '-') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-present" @click="handleGivePackage(scope.row)">赠送</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增/修改套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="权益详情" prop="detail">
          <el-input v-model="form.detail" type="textarea" :rows="4" placeholder="请输入权益详情" />
        </el-form-item>
        <el-form-item label="套餐图片" prop="image">
          <image-upload v-model="form.image" :limit="10" :file-size="5" />
        </el-form-item>
        <el-form-item label="价格" prop="parice">
          <el-input-number v-model="form.parice" :precision="2" :min="0" :step="0.01" placeholder="请输入价格"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品规格" prop="good_spec_id">
          <el-select v-model="form.good_spec_id" multiple filterable placeholder="请选择商品规格" style="width: 100%">
            <el-option v-for="option in specOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="option in statusOptions" :key="option.value" :label="option.value">{{ option.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 赠送套餐对话框 -->
    <el-dialog title="赠送套餐" :visible.sync="givePackageOpen" width="500px" append-to-body>
      <el-form ref="givePackageForm" :model="givePackageForm" :rules="givePackageRules" label-width="100px">
        <el-form-item label="套餐" prop="rights_id">
          <el-select v-model="givePackageForm.rights_id" placeholder="请选择套餐" filterable style="width: 100%"
            :disabled="!!selectedRightsId">
            <el-option v-for="option in rightsOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="user_id">
          <el-select v-model="givePackageForm.user_id" placeholder="请选择用户" filterable style="width: 100%">
            <el-option v-for="option in userOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="givePackageLoading" @click="submitGivePackage">确 定</el-button>
        <el-button @click="cancelGivePackage">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPackageList, addPackage, updatePackage, givePackage, getGoodSpecList, getUserList } from '@/api/api'
import ImageUpload from '@/components/ImageUpload'

export default {
  name: 'Rights',
  components: { ImageUpload },
  data() {
    return {
      loading: false,
      submitLoading: false,
      givePackageLoading: false,
      showSearch: true,
      rightsList: [],
      specOptions: [],
      specMap: {},
      userOptions: [],
      userMap: {},
      rightsOptions: [],
      statusOptions: [
        { label: '上架', value: 1 },
        { label: '下架', value: 0 }
      ],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      open: false,
      givePackageOpen: false,
      selectedRightsId: undefined,
      baseUrl: process.env.VUE_APP_BASE_API,
      queryParams: {
        page: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      form: {
        id: undefined,
        name: '',
        detail: '',
        image: '',
        parice: 0,
        good_spec_id: [],
        status: 1
      },
      givePackageForm: {
        rights_id: undefined,
        user_id: undefined
      },
      rules: {
        name: [
          { required: true, message: '套餐名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度需在 1 到 100 个字符', trigger: 'blur' }
        ],
        parice: [
          { required: true, message: '价格不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      givePackageRules: {
        rights_id: [
          { required: true, message: '请选择套餐', trigger: 'change' }
        ],
        user_id: [
          { required: true, message: '请选择用户', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getSpecOptions()
    this.getUserOptions()
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      getPackageList(this.queryParams)
        .then(res => {
          const { list, total } = this.normalizeResponse(res)
          this.rightsList = list
          this.total = total || list.length
          // 更新套餐选项
          this.rightsOptions = list.map(item => ({
            label: item.name || `套餐${item.id}`,
            value: item.id
          }))
        })
        .finally(() => {
          this.loading = false
        })
    },
    normalizeResponse(res) {
      if (!res) {
        return { list: [], total: 0 }
      }
      if (Array.isArray(res)) {
        return { list: res, total: res.length }
      }
      if (Array.isArray(res.rows)) {
        return { list: res.rows, total: res.total ?? res.rows.length }
      }
      if (Array.isArray(res.data)) {
        return { list: res.data, total: res.total ?? res.data.length }
      }
      if (res.data && Array.isArray(res.data.records)) {
        return { list: res.data.records, total: res.data.total ?? res.data.records.length }
      }
      if (res.data && Array.isArray(res.data.list)) {
        return { list: res.data.list, total: res.data.total ?? res.data.list.length }
      }
      if (Array.isArray(res.list)) {
        return { list: res.list, total: res.total ?? res.list.length }
      }
      if (Array.isArray(res.records)) {
        return { list: res.records, total: res.total ?? res.records.length }
      }
      return { list: [], total: 0 }
    },
    getSpecOptions() {
      getGoodSpecList({})
        .then(res => {
          const { list } = this.normalizeResponse(res)
          this.specOptions = list.map(item => ({
            label: `${item.name || `规格${item.id}`} (¥${item.price || '0.00'})`,
            value: item.id
          }))
          this.specMap = {}
          list.forEach(item => {
            this.specMap[item.id] = item.name || `规格${item.id}`
          })
        })
    },
    getUserOptions() {
      getUserList({})
        .then(res => {
          const { list } = this.normalizeResponse(res)
          this.userOptions = list.map(item => ({
            label: item.name || item.username || `用户${item.id}`,
            value: item.id
          }))
          this.userMap = {}
          list.forEach(item => {
            this.userMap[item.id] = item.name || item.username || `用户${item.id}`
          })
        })
    },
    getSpecName(id) {
      return this.specMap[id] || '-'
    },
    getSpecIdList(ids) {
      if (!ids) return []
      if (Array.isArray(ids)) {
        return ids.filter(Boolean)
      }
      if (typeof ids === 'string' && ids) {
        return ids.split(',').map(id => Number(id)).filter(Boolean)
      }
      return []
    },
    // 从 rights_goods 数组中获取商品规格列表
    getRightsGoodsList(row) {
      if (!row.rights_goods || !Array.isArray(row.rights_goods)) {
        // 兼容旧格式：直接从 good_spec_id 字段读取
        const specIds = this.getSpecIdList(row.good_spec_id)
        return specIds.map(specId => ({
          specId: specId,
          specName: this.getSpecName(specId)
        }))
      }
      return row.rights_goods.map(item => ({
        specId: item.goods_spec_id || item.spec?.id,
        specName: item.spec?.name || this.getSpecName(item.goods_spec_id || item.spec?.id)
      })).filter(item => item.specId)
    },
    getImageList(image) {
      if (!image) return []
      if (Array.isArray(image)) {
        return image.filter(Boolean)
      }
      if (typeof image === 'string' && image) {
        return image.split(',').filter(Boolean)
      }
      return []
    },
    getImageUrl(url) {
      if (!url) return ''
      if (/^https?:\/\//i.test(url)) {
        return url
      }
      if (this.baseUrl && url.startsWith(this.baseUrl)) {
        return url
      }
      if (this.baseUrl) {
        const prefix = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl
        const path = url.startsWith('/') ? url : `/${url}`
        return `${prefix}${path}`
      }
      return url
    },
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    reset() {
      this.form = {
        id: undefined,
        name: '',
        detail: '',
        image: '',
        parice: 0,
        good_spec_id: [],
        status: 1
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增套餐'
    },
    handleUpdate(row) {
      const targetId = row?.id ?? this.ids[0]
      if (!targetId) {
        this.$modal.msgWarning('请选择要修改的套餐')
        return
      }
      const record = this.rightsList.find(item => String(item.id) === String(targetId))
      if (!record) {
        this.$modal.msgWarning('未找到对应的套餐数据')
        return
      }
      // 处理图片格式：优先使用 images，兼容 image
      let imageValue = []
      const imageSource = record.images || record.image
      if (Array.isArray(imageSource)) {
        imageValue = imageSource.filter(Boolean)
      } else if (typeof imageSource === 'string' && imageSource) {
        imageValue = imageSource.split(',').filter(Boolean)
      }
      // 处理商品规格ID：优先从 rights_goods 数组中提取
      let specIds = []
      if (Array.isArray(record.rights_goods) && record.rights_goods.length > 0) {
        specIds = record.rights_goods
          .map(item => item.goods_spec_id || item.spec?.id)
          .filter(id => id !== undefined && id !== null)
          .map(id => Number(id))
          .filter(id => !isNaN(id))
      } else if (Array.isArray(record.good_spec_id)) {
        specIds = record.good_spec_id.map(id => Number(id)).filter(id => !isNaN(id))
      } else if (typeof record.good_spec_id === 'string' && record.good_spec_id) {
        specIds = record.good_spec_id.split(',').map(id => Number(id.trim())).filter(id => !isNaN(id))
      }

      // 价格优先使用 price，兼容 parice
      const price = record.price !== undefined && record.price !== null 
        ? Number(record.price) 
        : (record.parice !== undefined && record.parice !== null ? Number(record.parice) : 0)

      this.form = {
        id: record.id,
        name: record.name || '',
        detail: record.detail || '',
        image: imageValue.length > 0 ? imageValue.join(',') : '',
        parice: price,
        good_spec_id: specIds,
        status: record.status !== undefined && record.status !== null ? Number(record.status) : 1
      }
      this.$nextTick(() => {
        if (this.$refs.form && this.$refs.form.clearValidate) {
          this.$refs.form.clearValidate()
        }
      })
      this.open = true
      this.title = '修改套餐'
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        this.submitLoading = true
        const payload = {
          ...this.form
        }

        // 处理图片格式：确保是数组格式
        if (typeof payload.image === 'string' && payload.image) {
          payload.image = payload.image.split(',').filter(Boolean)
        } else if (Array.isArray(payload.image)) {
          payload.image = payload.image.filter(Boolean)
        } else {
          payload.image = []
        }

        // 处理商品规格ID：确保是数组格式
        if (!Array.isArray(payload.good_spec_id)) {
          if (typeof payload.good_spec_id === 'string' && payload.good_spec_id) {
            payload.good_spec_id = payload.good_spec_id.split(',').map(id => Number(id.trim())).filter(id => !isNaN(id))
          } else {
            payload.good_spec_id = []
          }
        } else {
          payload.good_spec_id = payload.good_spec_id.map(id => Number(id)).filter(id => !isNaN(id))
        }

        const request = payload.id ? updatePackage(payload) : addPackage({ ...payload, id: undefined })
        request
          .then(() => {
            this.$modal.msgSuccess(payload.id ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = selection.length === 0
    },
    handleGivePackage(row) {
      const targetId = row?.id ?? this.ids[0]
      if (targetId) {
        this.selectedRightsId = targetId
        this.givePackageForm.rights_id = targetId
      } else {
        this.selectedRightsId = undefined
        this.givePackageForm.rights_id = undefined
      }
      this.givePackageForm.user_id = undefined
      this.givePackageOpen = true
      this.$nextTick(() => {
        if (this.$refs.givePackageForm && this.$refs.givePackageForm.clearValidate) {
          this.$refs.givePackageForm.clearValidate()
        }
      })
    },
    cancelGivePackage() {
      this.givePackageOpen = false
      this.givePackageForm = {
        rights_id: undefined,
        user_id: undefined
      }
      this.selectedRightsId = undefined
      this.resetForm('givePackageForm')
    },
    submitGivePackage() {
      this.$refs.givePackageForm.validate(valid => {
        if (!valid) {
          return
        }
        this.givePackageLoading = true
        givePackage({
          rights_id: this.givePackageForm.rights_id,
          user_id: this.givePackageForm.user_id
        })
          .then(() => {
            this.$modal.msgSuccess('赠送套餐成功')
            this.givePackageOpen = false
            this.cancelGivePackage()
          })
          .finally(() => {
            this.givePackageLoading = false
          })
      })
    },
    getStatusLabel(value) {
      const target = this.statusOptions.find(item => Number(item.value) === Number(value))
      return target ? target.label : '-'
    },
    getStatusTagType(value) {
      const match = Number(value)
      if (match === 1) {
        return 'success'
      }
      if (match === 0) {
        return 'danger'
      }
      return 'default'
    }
  }
}
</script>

<style scoped lang="scss">
.image-preview {
  display: flex;
  align-items: center;
}

.image-preview__item {
  width: 48px;
  height: 48px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 6px;
}

.image-preview__more {
  font-size: 12px;
  color: #909399;
}
</style>

